/**
 * 腾讯位置服务工具类
 * 文档：https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview
 */

// 腾讯地图配置
const TENCENT_MAP_KEY = 'T23BZ-PTJRT-4GPX3-LI7MB-YOHKH-NSFAT'; // 你的腾讯地图key

/**
 * 位置信息接口
 */
export interface LocationInfo {
  latitude: number;      // 纬度
  longitude: number;     // 经度
  name?: string;         // 位置名称
  address?: string;      // 详细地址
  province?: string;     // 省份
  city?: string;         // 城市
  district?: string;     // 区县
}

/**
 * 腾讯地图服务类
 */
export class TencentMapService {
  
  /**
   * 打开地图选择位置（微信原生）
   * @returns Promise<LocationInfo>
   */
  static chooseLocation(): Promise<LocationInfo> {
    return new Promise((resolve, reject) => {
      wx.chooseLocation({
        success: (res) => {
          console.log('选择位置成功:', res);
          resolve({
            latitude: res.latitude,
            longitude: res.longitude,
            name: res.name,
            address: res.address
          });
        },
        fail: (error) => {
          console.error('选择位置失败:', error);
          if (error.errMsg.includes('cancel')) {
            reject({ message: '用户取消选择位置', code: 'USER_CANCEL' });
          } else if (error.errMsg.includes('auth')) {
            wx.showModal({
              title: '需要位置权限',
              content: '请在设置中开启位置权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting();
                }
              }
            });
            reject({ message: '缺少位置权限', code: 'NO_PERMISSION' });
          } else {
            reject({ message: '选择位置失败', code: 'UNKNOWN', error });
          }
        }
      });
    });
  }

  /**
   * 获取当前位置
   * @returns Promise<LocationInfo>
   */
  static getCurrentLocation(): Promise<LocationInfo> {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02', // 返回可以用于 wx.openLocation 的坐标
        success: async (res) => {
          console.log('获取当前位置成功:', res);
          
          try {
            // 逆地址解析获取详细地址
            const addressInfo = await this.reverseGeocoder({
              latitude: res.latitude,
              longitude: res.longitude
            });
            
            resolve({
              latitude: res.latitude,
              longitude: res.longitude,
              ...addressInfo
            });
          } catch (error) {
            // 即使逆地址解析失败，也返回坐标
            resolve({
              latitude: res.latitude,
              longitude: res.longitude
            });
          }
        },
        fail: (error) => {
          console.error('获取位置失败:', error);
          if (error.errMsg.includes('auth')) {
            wx.showModal({
              title: '需要位置权限',
              content: '请在设置中开启位置权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting();
                }
              }
            });
            reject({ message: '缺少位置权限', code: 'NO_PERMISSION' });
          } else {
            reject({ message: '获取位置失败', code: 'UNKNOWN', error });
          }
        }
      });
    });
  }

  /**
   * 在地图上查看位置
   * @param location 位置信息
   */
  static openLocation(location: LocationInfo): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!location.latitude || !location.longitude) {
        wx.showToast({
          title: '位置信息不完整',
          icon: 'none'
        });
        reject({ message: '位置信息不完整' });
        return;
      }

      wx.openLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        name: location.name || '商家位置',
        address: location.address || '',
        scale: 16,
        success: () => {
          console.log('打开地图成功');
          resolve();
        },
        fail: (error) => {
          console.error('打开地图失败:', error);
          wx.showToast({
            title: '打开地图失败',
            icon: 'none'
          });
          reject({ message: '打开地图失败', error });
        }
      });
    });
  }

  /**
   * 逆地址解析（坐标转地址）
   * 使用腾讯位置服务 WebService API
   * @param location 坐标
   * @returns Promise<地址信息>
   */
  static reverseGeocoder(location: { latitude: number; longitude: number }): Promise<{
    address: string;
    province: string;
    city: string;
    district: string;
    name?: string;
  }> {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        data: {
          location: `${location.latitude},${location.longitude}`,
          key: TENCENT_MAP_KEY,
          get_poi: 1
        },
        success: (res: any) => {
          console.log('逆地址解析结果:', res);
          
          if (res.data.status === 0) {
            const result = res.data.result;
            const addressComponent = result.address_component;
            
            resolve({
              address: result.address,
              province: addressComponent.province,
              city: addressComponent.city,
              district: addressComponent.district,
              name: result.formatted_addresses?.recommend || result.address
            });
          } else {
            console.error('逆地址解析失败:', res.data);
            reject({ 
              message: res.data.message || '地址解析失败',
              code: res.data.status
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          reject({ message: '网络请求失败', error });
        }
      });
    });
  }

  /**
   * 地址解析（地址转坐标）
   * @param address 地址
   * @param region 指定地区（可选，如"北京市"）
   * @returns Promise<坐标信息>
   */
  static geocoder(address: string, region?: string): Promise<{
    latitude: number;
    longitude: number;
    address: string;
    province: string;
    city: string;
    district: string;
  }> {
    return new Promise((resolve, reject) => {
      const data: any = {
        address: address,
        key: TENCENT_MAP_KEY
      };
      
      if (region) {
        data.region = region;
      }

      wx.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        data: data,
        success: (res: any) => {
          console.log('地址解析结果:', res);
          
          if (res.data.status === 0) {
            const result = res.data.result;
            const location = result.location;
            const addressComponent = result.address_components;
            
            resolve({
              latitude: location.lat,
              longitude: location.lng,
              address: result.title || address,
              province: addressComponent.province,
              city: addressComponent.city,
              district: addressComponent.district
            });
          } else {
            console.error('地址解析失败:', res.data);
            reject({ 
              message: res.data.message || '地址解析失败',
              code: res.data.status
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          reject({ message: '网络请求失败', error });
        }
      });
    });
  }

  /**
   * 地点搜索
   * @param keyword 搜索关键词
   * @param location 当前位置（可选）
   * @param region 搜索地区（可选）
   * @returns Promise<搜索结果列表>
   */
  static searchPlace(
    keyword: string,
    location?: { latitude: number; longitude: number },
    region?: string
  ): Promise<Array<{
    id: string;
    title: string;
    address: string;
    latitude: number;
    longitude: number;
    province: string;
    city: string;
    district: string;
  }>> {
    return new Promise((resolve, reject) => {
      const data: any = {
        keyword: keyword,
        key: TENCENT_MAP_KEY,
        page_size: 20
      };

      if (location) {
        data.boundary = `nearby(${location.latitude},${location.longitude},1000)`; // 1000米范围
      } else if (region) {
        data.boundary = `region(${region},0)`;
      }

      wx.request({
        url: 'https://apis.map.qq.com/ws/place/v1/search',
        data: data,
        success: (res: any) => {
          console.log('地点搜索结果:', res);
          
          if (res.data.status === 0) {
            const results = res.data.data.map((item: any) => ({
              id: item.id,
              title: item.title,
              address: item.address,
              latitude: item.location.lat,
              longitude: item.location.lng,
              province: item.ad_info?.province || '',
              city: item.ad_info?.city || '',
              district: item.ad_info?.district || ''
            }));
            
            resolve(results);
          } else {
            console.error('地点搜索失败:', res.data);
            reject({ 
              message: res.data.message || '搜索失败',
              code: res.data.status
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          reject({ message: '网络请求失败', error });
        }
      });
    });
  }

  /**
   * 计算两点之间的距离（米）
   * @param from 起点
   * @param to 终点
   * @returns 距离（米）
   */
  static calculateDistance(
    from: { latitude: number; longitude: number },
    to: { latitude: number; longitude: number }
  ): number {
    const radLat1 = (from.latitude * Math.PI) / 180;
    const radLat2 = (to.latitude * Math.PI) / 180;
    const a = radLat1 - radLat2;
    const b = (from.longitude * Math.PI) / 180 - (to.longitude * Math.PI) / 180;
    
    let distance = 2 * Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    );
    
    distance = distance * 6378137; // 地球半径（米）
    distance = Math.round(distance * 10000) / 10000;
    
    return distance;
  }

  /**
   * 格式化距离显示
   * @param distance 距离（米）
   * @returns 格式化后的距离字符串
   */
  static formatDistance(distance: number): string {
    if (distance < 1000) {
      return `${Math.round(distance)}m`;
    } else {
      return `${(distance / 1000).toFixed(1)}km`;
    }
  }
}

// 导出默认实例
export default TencentMapService;



